package com.jsbj.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.Excel.CustomException;
//import com.jsbj.enums.ConfigPushTypeEnum;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
//import com.jsbj.user.entities.ConfigPushmessage;
import com.jsbj.user.entities.SysNotice;
import com.jsbj.user.entities.SysUser;
import com.jsbj.user.mapper.SysNoticeMapper;
//import com.jsbj.user.service.IConfigPushmessageService;
import com.jsbj.user.service.ISysNoticeService;
import com.jsbj.user.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * <p>
 * 通知表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2023-05-11
 */
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice> implements ISysNoticeService {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ISysUserService sysUserService;
//    @Autowired
//    private IConfigPushmessageService configPushmessageService;

    @Override
    public IPage<SysNotice> pageList(String inParam) {

        String userId = RequestHeaderUtils.getUserId(request);

//        JSONObject object = JSONObject.parseObject(inParam);

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysNotice> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<SysNotice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysNotice::getDisabled,0);
        queryWrapper.orderByDesc(SysNotice::getCreateTime);

        IPage<SysNotice> sysNoticePage = baseMapper.selectPage(page, queryWrapper);
        List<SysNotice> records = sysNoticePage.getRecords();
        for (SysNotice record : records) {

            String createrId = record.getCreaterId();
            String userIds = record.getUserIds();
            Integer status = record.getStatus();

            //创建人
            SysUser user = sysUserService.getById(createrId);
            if(null != user){
                record.setCreateName(user.getUserName());
            }
            //已读 未读
            if(1 == status){
                record.setUnRead(userIds.split(",").length);
                record.setRead(0);
            }else{
//                List<ConfigPushmessage> list = configPushmessageService.list(Wrappers.<ConfigPushmessage>lambdaQuery()
//                        .eq(ConfigPushmessage::getPushType, ConfigPushTypeEnum.QE_NOTICE.getCode())
//                        .eq(ConfigPushmessage::getForeignTableId, record.getId())
//                        .eq(ConfigPushmessage::getDisabled,0));
//
//                int unRead = list.stream().filter(x -> 0 == x.getDealStatus()).collect(Collectors.toList()).size();//未读
//                int read = list.stream().filter(x -> 2 == x.getDealStatus()).collect(Collectors.toList()).size();//已读
//                record.setRead(read);
//                record.setUnRead(unRead);
            }

        }
        return sysNoticePage;
    }

    @Override
    public Boolean add(SysNotice sysNotice) {

        String userId = RequestHeaderUtils.getUserId(request);

        if(StringUtils.isEmpty(sysNotice.getUserIds()) || StringUtils.isEmpty(sysNotice.getContent())){
            throw new CustomException("必填项不能为空！");
        }

        //保存通知
        sysNotice.setStatus(1);
        sysNotice.setDisabled(0);
        sysNotice.setCreaterId(userId);
        sysNotice.setCreateTime(new Date());
        sysNotice.setUpdateId(userId);
        sysNotice.setUpdateTime(new Date());

        return save(sysNotice);
    }

    @Override
    public Boolean update(SysNotice sysNotice) {

        String userId = RequestHeaderUtils.getUserId(request);

        if(StringUtils.isEmpty(sysNotice.getUserIds()) || StringUtils.isEmpty(sysNotice.getContent())){
            throw new CustomException("必填项不能为空！");
        }

        //保存通知
        sysNotice.setUpdateId(userId);
        sysNotice.setUpdateTime(new Date());
        return updateById(sysNotice);
    }

    @Override
    public SysNotice detail(String id) {

        SysNotice sysNotice = getById(id);
        StringJoiner userNames = new StringJoiner(",");
        if(null != sysNotice){
            String createrId = sysNotice.getCreaterId();
            SysUser sysUser = sysUserService.getById(createrId);
            if(null != sysUser){
                sysNotice.setCreateName(sysUser.getUserName());
            }

            String userIds = sysNotice.getUserIds();
            if(StringUtils.isNotEmpty(userIds)){
                String[] split = userIds.split(",");
                for (String userId : split) {
                    sysUser = sysUserService.getById(userId);
                    if(null != sysUser){
                        userNames.add(sysUser.getUserName());
                    }
                }
            }
        }
        sysNotice.setUserNames(userNames.toString());
        return sysNotice;
    }

    @Override
    public Boolean delete(String id) {
        String userId = RequestHeaderUtils.getUserId(request);

        SysNotice sysNotice = getById(id);
        sysNotice.setDisabled(1);
        sysNotice.setUpdateId(userId);
        sysNotice.setUpdateTime(new Date());

        return updateById(sysNotice);
    }

    @Override
    public Boolean publish(String id) {

        Boolean flag = false;

        String userId = RequestHeaderUtils.getUserId(request);

        SysNotice sysNotice = getById(id);
        String userIds = sysNotice.getUserIds();

        sysNotice.setStatus(2);
        sysNotice.setUpdateId(userId);
        sysNotice.setUpdateTime(new Date());
        flag =updateById(sysNotice);

        String[] userIdArr = userIds.split(",");
        for (String uid : userIdArr) {

//            ConfigPushmessage configPushmessage = new ConfigPushmessage();
//            configPushmessage.setForeignTableId(id);
//            configPushmessage.setPushComment(sysNotice.getContent());
//            configPushmessage.setPushType(ConfigPushTypeEnum.QE_NOTICE.getCode());
//
//            SysUser user = sysUserService.getById(uid);
//            if(null != user){
//                configPushmessage.setRecipientUser(user.getUserName());
//            }
//            configPushmessage.setRecipientUserid(uid);
//            configPushmessage.setDealStatus(0);
//            configPushmessage.setDisabled(0);
//            configPushmessage.setCreaterId(userId);
//            configPushmessage.setCreateTime(new Date());
//            configPushmessage.setUpdateId(userId);
//            configPushmessage.setUpdateTime(new Date());
//
//            flag = configPushmessageService.save(configPushmessage);

        }
        return flag;
    }

//    @Override
//    public ConfigPushmessage queryList(String userId) {
//
//        List<ConfigPushmessage> list = configPushmessageService.list(Wrappers.<ConfigPushmessage>lambdaQuery()
//                .eq(ConfigPushmessage::getDisabled, 0)
//                .eq(ConfigPushmessage::getDealStatus, 0)
//                .eq(ConfigPushmessage::getRecipientUserid, userId)
//                .eq(ConfigPushmessage::getPushType,ConfigPushTypeEnum.QE_NOTICE.getCode())
//                .orderByDesc(ConfigPushmessage::getCreateTime));
//
//        for (ConfigPushmessage configPushmessage : list) {
//            configPushmessage.setDealStatus(2);
//            configPushmessage.setUpdateId(userId);
//            configPushmessage.setUpdateTime(new Date());
//            configPushmessageService.updateById(configPushmessage);
//        }
//        if(!list.isEmpty()){
//            return list.get(0);
//        }
//
//        return null;
//    }
}
